using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FactoryAutoMatic.Dao
{
  class GetApi
  {

    public static string HttpGET(string url)
    {//创建
      HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
      //设置请求方法
      httpWebRequest.Method = "GET";
      //请求超时时间
      httpWebRequest.Timeout = 20000;
      //发送请求
      HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
      //利用Stream流读取返回数据
      StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
      //获得最终数据    一般是json
      string responseContent = streamReader.ReadToEnd();
      streamReader.Close();
      httpWebResponse.Close();

      return responseContent;

    }

    public string HttpPost(string postUrl, string paramData)
    {
      string ret = string.Empty;
      Encoding dataEncode = null;
      string header = "";
      try
      {
        if (dataEncode == null)
          dataEncode = Encoding.UTF8;

        byte[] byteArray = dataEncode.GetBytes(paramData); //转化
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
        webReq.Method = "POST";
        webReq.ContentType = "application/json";

        webReq.Headers.Add("Session-Key", header);

        webReq.ContentLength = byteArray.Length;
        Stream newStream = webReq.GetRequestStream();
        newStream.Write(byteArray, 0, byteArray.Length);//写入参数
        newStream.Close();
        HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
        var c = response.GetResponseStream();
        StreamReader sr = new StreamReader(c, Encoding.UTF8);

        Char[] read = new Char[4000];
        int count = sr.Read(read, 0, read.Length);

        while (count > 0)
        {
          String str = new String(read, 0, count);
          ret += str;

          count = sr.Read(read, 0, read.Length);
        }

        sr.Close();
        response.Close();
        newStream.Close();

      }
      catch (Exception ex)
      {
        throw;
      }
      return ret;
    }

  }
}
